package top.maybesix.base.delegate

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.InputMethodManager
import top.maybesix.base.base.IActivity

/**
 * @author MaybeSix
 * @date 2020/4/29
 * @desc Activity的代理接口实现.
 */
open class ActivityDelegateImpl(private val activity: Activity) : ActivityDelegate {

    private val iActivity = activity as IActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        // 在界面未初始化之前调用的初始化窗口
        iActivity.initWidows()
        initLayout()
        iActivity.initBefore()
        iActivity.initView()
        iActivity.initEvent()
        iActivity.initAdapter()
        iActivity.initListener()
        iActivity.initData()

    }

    /**
     * 初始化布局
     */
    protected open fun initLayout() {
        if (iActivity.getLayoutId() > 0) {
            activity.setContentView(iActivity.getLayoutId())
            initSoftKeyboard()
        }
    }

    /**
     * 初始化软键盘
     */
    protected open fun initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView()?.setOnClickListener { hideSoftKeyboard() }
    }

    /**
     * 和 setContentView 对应的方法
     */
    open fun getContentView(): ViewGroup? {
        return activity.findViewById(Window.ID_ANDROID_CONTENT)
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        val view = activity.currentFocus
        if (view != null) {
            val manager =
                activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    override fun onStart() {
    }

    override fun onResume() {
    }

    override fun onPause() {
    }

    override fun onStop() {
    }

    override fun onDestroy() {
        hideSoftKeyboard()
    }

    override fun onSaveInstanceState(activity: Activity?, outState: Bundle?) {

    }
}